Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
The number of elements initialized in nums1 and nums2 are m and n respectively.

题目大意:nums1和nums2为2个已经排好序的数组,将nums2合并到nums1中,nums1有足够的空间

题目难度:Easy

/**
 * Created by gzdaijie on 16/6/4
 * 因为nums1有足够的空间,所以选择从大到小合并
 * 时间复杂度O(N),空间复杂度O(1)
 */
public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int k = m + n;
        m--; n--;
        while (--k >= 0) {
            if (n < 0) return; // nums2已经合并完成
            if (m >= 0 && nums1[m] >= nums2[n]) { 
                nums1[k] = nums1[m--];
            } else {
                nums1[k] = nums2[n--];
            }
        }
    }
}
gzdaijie            updated 2016-06-04 16:20:49

results matching ""

    No results matching ""